/*
 * @Author: lirl liruilu@cnhealth.com
 * @Date: 2022-09-16 17:52:39
 * @LastEditors: lirl liruilu@cnhealth.com
 * @LastEditTime: 2022-09-19 21:07:46
 * @FilePath: /cgjoy-class-online/src/pages/pc/lecturer/upload-courses/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { useEffect, useRef, useState } from 'react';
import classnames from 'classnames';
import styles from './index.less';
import type { EditInstance } from './components/edit';
import EditView, { ActionRefType } from './components/edit';
import type { UploadInstance } from './components/upload';
import UploadView from './components/upload';
import { Button, message } from 'antd';
import { allGet, allPost } from '@/services/pc';
import classNames from 'classnames';
import { useHistory, useModel } from 'umi';
type TabType = '编辑课程数据' | '素材/课时管理';
const tabs: TabType[] = ['编辑课程数据', '素材/课时管理'];
const Index = () => {
  const { location } = useHistory();
  const { query = {} } = location as any;
  const { userInfo } = useModel('user');

  const [active, setActive] = useState<TabType>(
    query.tabindex == 1 ? '素材/课时管理' : '编辑课程数据',
  );
  const [noverify, setNoverify] = useState(false);
  const actionRef = useRef<EditInstance>();
  const uploadActionRef = useRef<UploadInstance>();
  const history = useHistory();
  /**
   * 获取课程详情数据
   */
  const { classid = 0 } = (history.location as any)?.query;
  const onSubmit = async (postsubmit, noMessage = false) => {
    const data = await actionRef.current?.getData(postsubmit);
    const flag = await actionRef.current?.validateTinymce();
    if (!flag) {
      message.warning('请先编辑课程详情内容');
      return;
    }
    const data2 = await uploadActionRef.current?.getData();
    data.attach_ids = [...data.attach_ids, ...data2.attach_ids].join(',');
    if (data2.lesson_ids && Array.isArray(data2.lesson_ids)) {
      data.lesson_ids = data2.lesson_ids.join(',');
    }
    if (data2.chapter_ids && Array.isArray(data2.chapter_ids)) {
      data.chapter_ids = data2.chapter_ids.join(',');
    }
    if (data2.lesson_orders) {
      data.lesson_orders = data2.lesson_orders;
    }
    const response = await allPost({ data: { ...data, nocontract: Number(noverify) } });
    if (noMessage) {
      return response.success;
    }
    if (response.success) {
      if (postsubmit === 'preview') {
        // return window.open(`/center/lecturer/detail/${response?.data?.sid}?type=preview`);
        return window.open(`/center/lecturer/detail/${response?.data?.classid}?type=preview`);
      }
      message.success(postsubmit === 'post' ? '发布成功' : '保存成功', 1.5, () => {
        if (postsubmit === 'post') {
          // 管理员
          if (userInfo.isadmin == 1) {
            window.location.href = `/center/courses/detail/${response?.data?.classid}`;
          } else {
            window.location.href = `/lecturer`;
          }

          //history.push(`/center/courses/detail/${response?.data?.classid}`);
        }
      });
    }
  };
  const onTabChange = async (str) => {
    if (str === '素材/课时管理') {
      actionRef.current
        ?.validateFields()
        .then(async () => {
          const flag = await actionRef.current?.validateTinymce();
          if (!flag) {
            message.warning('请先编辑课程详情内容');
            return;
          }
          uploadActionRef.current?.init();
          setActive(str);
        })
        .catch(() => {
          message.warning('请先完善课程基本数据');
        });
    } else {
      setActive(str);
    }
  };
  // 这里也要发个详情请求，为了赋值给“认证免签”
  const init = async () => {
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid /* classid */ },
    });
    const course = classid ? response?.data?.course : response?.data?.coursetmp?.data;
    setNoverify(course?.nocontract == 1 ? true : false);
  };
  useEffect(() => {
    init();
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div>
          <h1>上传课程</h1>
          {tabs.map((str) => (
            <span
              key={str}
              onClick={() => onTabChange(str)}
              className={classnames({ [styles.active]: active === str })}
            >
              {str}
            </span>
          ))}
        </div>
      </div>
      <div className={styles.content}>
        <div style={{ display: active === '编辑课程数据' ? 'block' : 'none' }}>
          <EditView ref={actionRef} />
        </div>
        <div style={{ display: active === '编辑课程数据' ? 'none' : 'block' }}>
          <UploadView
            ref={uploadActionRef}
            onSaveSort={() => onSubmit(!classid ? 'save' : 'post', true)}
          />
        </div>
      </div>
      <div className={styles.footer}>
        <span className={styles.tips}>勾选之后，观看课程视频不再需要签署合同和实名认证。</span>
        <div className={styles.mianqian}>
          {' '}
          <i
            className={classNames(styles.icon, { [styles.checked]: noverify })}
            onClick={() => {
              setNoverify(!noverify);
            }}
          />
          免签免认证
        </div>
        <Button type="ghost" onClick={() => onSubmit('preview')}>
          预览
        </Button>
        {!classid && (
          <Button type="ghost" onClick={() => onSubmit('save')}>
            保存
          </Button>
        )}
        <Button onClick={() => onSubmit('post')} type="primary">
          发布课程
        </Button>
      </div>
    </div>
  );
};
export default Index;
